package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.*;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.impl.EmployeeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee" )
public class EmployeeController {

    @Autowired
    private EmployeeServiceImpl employeeService;


    //登录
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //查询数据库
        if(employee==null||
                StringUtils.isEmpty(employee.getUsername())||
                StringUtils.isEmpty(employee.getPassword())){
            return R.error("用户名或密码不得为空");
        }
        //用户
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(qw);


        if(emp==null)
            return R.error("用户不存在");
        //密码
        if(!emp.getPassword().equals(password)){
            emp.setPassword(null);
            return  R.error("密码错误，登录失败");
        }


        //状态
        if(emp.getStatus()==0)
            return R.error("用户禁用，登录失败");

        else {
            request.getSession().setAttribute("employee",emp.getId());
            emp.setPassword(null);
            return R.success(emp);
        }

    }
    @PostMapping("/logout")
    public R<String> logout(HttpSession httpSession){
        httpSession.removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */

    //Request URL:http://localhost:8080/employee所以不用加了

    @PostMapping
    public R<String> save(HttpSession session,@RequestBody Employee employee){
        log.info("新增员工，员工信息：{}",employee.toString());
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
      //  employee.setCreateTime(LocalDateTime.now());
      //  employee.setUpdateTime(LocalDateTime.now());

        //当前登录的用户

     //   Long id = (Long)session.getAttribute("employee");
     //   employee.setCreateUser(id);
      //  employee.setUpdateUser(id);

        employeeService.save(employee);
        return R.success("新增员工成功");
    }


    /**
     * 员工信息的分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);

        //分页构造器
        Page pageInfo=new Page(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        //添加排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);


        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    /**
     *  修改员工信息
     * @param session
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpSession session,@RequestBody Employee employee){

        log.info(employee.toString());

        Long id=Thread.currentThread().getId();
        log.info("线程id为："+id);
        //1、修改员工数据 update_time
  //      employee.setUpdateTime(LocalDateTime.now());

//2、修改员工数据 update_user 从sesion中获取员工id
  //      Long empId = (Long) session.getAttribute("employee");

//3、调用业务层修改员工信息 updateById()
   //     employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");

    }


    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee==null){
            return R.error("员工不存在");
        }else{
            return R.success(employee);
        }

    }





}
